import { Component, EventEmitter, Input, NgZone, OnInit, Output, ViewChild } from '@angular/core';
import { ApiService } from 'src/app/services/api.service';
import { DeptDto } from 'src/app/models/sys/dept.dto';
import { RoleDto } from 'src/app/models/sys/role.dto';
import { DictDto } from 'src/app/models/sys/dict.dto';
import { Consts } from 'src/app/consts/consts';
import { NzTreeComponent, NzTreeNodeOptions } from 'ng-zorro-antd/tree';
import { DeptQueryParam } from 'src/app/models/param/dept-query.param';
import { TreeUtils } from 'src/app/utils/tree.util';
import { BehaviorSubject } from 'rxjs';
import { NzFormatEmitEvent } from 'ng-zorro-antd/core/tree';
import { RoleDataScopeParam } from 'src/app/models/param/role-data-scope.param';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-role-data-perms',
  templateUrl: './role-data-perms.component.html',
  styleUrl: './role-data-perms.component.less'
})
export class RoleDataPermsComponent implements OnInit {
  @Input() dataPermSubject!: BehaviorSubject<number>;
  @Output() dataPermEvent = new EventEmitter<boolean>();

  @ViewChild('nzTreeComponent') tree!: NzTreeComponent;

  role = new RoleDto();
  // 部门树形
  depts: DeptDto[] = [];
  deptNodes: NzTreeNodeOptions[] = [];

  defaultCheckedKeys: string[] = [];
  defaultSelectedKeys: string[] = [];
  defaultExpandedKeys = [];

  dataScopes: DictDto[] = [];
  selectedDataScope?: string;

  constructor(private _api: ApiService,
    private _message: NzMessageService,
    private _zone: NgZone) { }

  ngOnInit(): void {
    this.getDepts();
  }

  getDataScopes() {
    this._api.getDataScopes().subscribe((resp) => {
      if (resp.code == Consts.RESP_OK && resp.data) {
        this.dataScopes = resp.data;
      }
    });
  }

  getDepts() {
    const param = new DeptQueryParam();
    param.pageNum = 1;
    param.pageSize = 10000;

    this._api.getDeptTree(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK && resp.data) {
        this.depts = resp.data;

        this.deptNodes = TreeUtils.convertDeptToTreeNodes(this.depts);

        console.log('tree converted');

        // 需要nzData赋值后，再设置默认选择项
        this.getDataScopes();

        this.dataPermSubject.subscribe((value) => {
          console.log(`roleId param got ${value}`);
          this._api.getRoleDetail(value).subscribe((resp) => {
            if (resp.code == Consts.RESP_OK && resp.data) {
              this.role = resp.data;
              this.defaultCheckedKeys = this.role.depts.map(x => String(x.deptId));
              console.log(`default selected depts ${this.defaultCheckedKeys.join(",")}`);
              if (this.role.dataScope != null) {
                this.selectedDataScope = String(this.role.dataScope);
              }
            }
          });
        });
      }
    });
  }

  nzClick(event: NzFormatEmitEvent): void {
    console.log(event);
  }

  nzCheck(event: NzFormatEmitEvent): void {
    console.log(`nzCheck ${event.keys}`);
    //  this.selectedNodes = event.checkedKeys?? [];
  }

  onAssign(event: UIEvent) {
    event.preventDefault();

    if (this.selectedDataScope == null) {
      this._message.warning("请选择权限范围");
      return;
    }

    const param = new RoleDataScopeParam();
    param.roleId = this.role.roleId;
    param.dataScope = Number(this.selectedDataScope);
    const nodes = this.tree.getCheckedNodeList();

    param.deptIds = nodes.map(x => Number(x.key));

    this._api.updateAuthDataScope(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK) {
        this._message.info("设置成功");
        this.resetModal();
        this.dataPermEvent.emit(true);
      } else {
        this._message.warning("设置失败:" + resp.message);
      }
    });
  }

  onCancel(event: UIEvent) {
    event.preventDefault();
    this.dataPermEvent.emit(false);
  }

  resetModal() {
    this.selectedDataScope = undefined;
  }

  dataScopeChange(value: string) {
    console.log(`dataScopeChange to ${value}`);
  }
}
